package com.realnet.vpspack.Services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.vpspack.Entity.SiteBuilder;
import com.realnet.vpspack.Repository.SiteBuilderRepository;

@Service
public class SiteBuilderService {
	@Autowired
	private SiteBuilderRepository Repository;
	@Autowired
	private AppUserServiceImpl userService;
	@Autowired
	private RealmService realmService;

	public SiteBuilder Savedata(SiteBuilder data) {

		data.setUpdatedBy(getUser().getUserId());
		data.setCreatedBy(getUser().getUserId());
		data.setAccountId(getUser().getAccount().getAccount_id());
		SiteBuilder save = Repository.save(data);
		return save;
	}

//	get all with pagination
	public Page<SiteBuilder> getAllWithPagination(Pageable page) {
		return Repository.findAll(page, getUser().getUserId());
	}

	public List<SiteBuilder> getdetails() {
		List<Realm> realm = realmService.findByUserId(getUser().getUserId());
		List<SiteBuilder> all = Repository.findAll(getUser().getUserId());

		return all;
	}

	public SiteBuilder getdetailsbyId(Integer id) {
		return Repository.findById(id).get();
	}

	public void delete_by_id(Integer id) {
		Repository.deleteById(id);
	}

	public SiteBuilder update(SiteBuilder data, Integer id) {
		SiteBuilder old = Repository.findById(id).get();

		if (data.getName() != null) {
			old.setName(data.getName());
		}

		if (data.getDescription() != null) {
			old.setDescription(data.getDescription());
		}

		if (data.getModel() != null) {
			old.setModel(data.getModel());
		}

		// isActive is boolean, use Boolean wrapper to check null safety
		if (data.isActive() != old.isActive()) {
			old.setActive(data.isActive());
		}

		if (data.getPrompt() != null) {
			old.setPrompt(data.getPrompt());
		}

		old.setUpdatedBy(getUser().getUserId());

		final SiteBuilder test = Repository.save(old);
		return test;
	}

	public AppUser getUser() {
		AppUser user = userService.getLoggedInUser();
		return user;

	}
}
