package com.rehome.jpahefengweather.service.Impl;


import com.rehome.jpahefengweather.dao.NmcCityRepository;
import com.rehome.jpahefengweather.dao.NmcProvinceRepository;
import com.rehome.jpahefengweather.entity.NmcCity;
import com.rehome.jpahefengweather.entity.NmcProvince;
import com.rehome.jpahefengweather.service.NmcCityService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class NmcCityServiceImpl  implements NmcCityService {

    @Resource
    private NmcCityRepository nmcCityRepository;
    @Resource
    private NmcProvinceRepository nmcProvinceRepository;

    @Override
    public NmcProvince findProvinceByCode(String code) {
        return this.nmcProvinceRepository.findByCode(code);
    }

    @Override
    public NmcCity findCityByCode(String code) {
        return this.nmcCityRepository.findByCode(code);
    }


    @Override
    public void saveProvince(NmcProvince province) {
        if(province!=null){
            Date now = new Date();
            NmcProvince provinceDB=this.nmcProvinceRepository.findByCode(province.getCode());
            if(provinceDB!=null){
                provinceDB.setName(province.getName());
                provinceDB.setUrl(province.getUrl());
                provinceDB.setLastUpdateDate(now);
                this.nmcProvinceRepository.save(provinceDB);
            }else{
                province.setLastUpdateDate(now);
                province.setCreateDate(now);
                this.nmcProvinceRepository.save(province);
            }
        }
    }

    @Override
    public void saveCity(NmcCity city) {
        if(city!=null){
            Date now = new Date();
            NmcCity cityDB=this.nmcCityRepository.findByCode(city.getCode());
            if(cityDB!=null){
                cityDB.setCity(city.getCity());
                cityDB.setProvince(city.getProvince());
                cityDB.setUrl(city.getUrl());
                cityDB.setLastUpdateDate(now);
                this.nmcCityRepository.save(cityDB);
            }else{
                city.setLastUpdateDate(now);
                city.setCreateDate(now);
                this.nmcCityRepository.save(city);
            }
        }
    }

    @Override
    public List<NmcCity> findAllCityList() {
        return this.nmcCityRepository.findAll();
    }
}
