package com.realnet.basic.Services;
import com.realnet.basic.Repository.Create_new_habitRepository;
import com.realnet.basic.Entity.Create_new_habit
;import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.realnet.SequenceGenerator.Service.SequenceService;
import org.springframework.data.domain.Page;
import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.users.entity1.AppUser;




import com.realnet.basic.Entity.Frequency;
import com.realnet.basic.Services.FrequencyService;



	import org.springframework.stereotype.Service;

@Service
 public class Create_new_habitService {
@Autowired
private Create_new_habitRepository Repository;
	@Autowired
	private AppUserServiceImpl userService; 
@Autowired
	private RealmService realmService;



@Autowired
	private FrequencyService frequencyserv;

public Create_new_habit Savedata(Create_new_habit data) {





 
if (data.getFrequency() != null) {
		try {	
  int frequencyId = Integer.valueOf(data.getFrequency());
Frequency get =  frequencyserv.getdetailsbyId(frequencyId);
			if (get != null) {

			data.setFrequencyname(get.getName());
}
} catch (NumberFormatException e) {
				System.out.println(" frequencyId is not integer..");
				// Invalid integer string — ignore or log
			}

		}

 


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


//	get all with pagination
	public Page<Create_new_habit> getAllWithPagination(Pageable page) {
		return Repository.findAll(page, getUser().getUserId());
	}			
public List<Create_new_habit> getdetails() {  
		List<Realm> realm = realmService.findByUserId(getUser().getUserId());
List<Create_new_habit> all = Repository.findAll(getUser().getUserId());
		
		return all ;		}


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


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


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

old.setDescription(data.getDescription());

old.setFrequency(data.getFrequency());

final Create_new_habit test = Repository.save(old);
		data.setUpdatedBy(getUser().getUserId());
  return test;} 






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

	}}
