package com.brframework.webapppatch.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.brframework.commoncms.core.cms.Select;
import com.brframework.commondb.core.AbstractEntityService;
import com.brframework.commondb.core.CommonRepository;
import com.brframework.commonweb.exception.HandleException;
import com.brframework.webapppatch.dao.PatchBranchDao;
import com.brframework.webapppatch.entity.PatchBranch;
import com.brframework.webapppatch.service.PatchBranchService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 分支
 * @author xu
 * @date 2019/11/14 10:31
 */
@Service
public class PatchBranchServiceImpl extends AbstractEntityService<PatchBranch, Long, Object>
        implements PatchBranchService {

    @Autowired
    PatchBranchDao patchBranchDao;

    @Override
    public CommonRepository<Long, PatchBranch> getRepository() {
        return patchBranchDao;
    }

    @Override
    public void updateBranch(Long id, String os, String brandName, String branchDetail) {
        PatchBranch patchBranch = accessObject(id);
        patchBranch.setId(id);
        patchBranch.setBranchName(brandName);
        patchBranch.setBranchDetail(branchDetail);
        save(patchBranch);
    }

    @Override
    public void updateBasePackage(String brandName, String packageUrl) {
        PatchBranch byBranchName = findByBranchName(brandName);
        if(byBranchName == null){
            throw new HandleException("分支【" + brandName + "】不存在，请在控制台创建");
        }
        byBranchName.setBasePackageUpdateDate(LocalDateTime.now());
        byBranchName.setBasePackageUrl(packageUrl);
        Long size = Long.parseLong(HttpUtil.createRequest(Method.HEAD, packageUrl).execute().header("Content-Length"));
        byBranchName.setBasePackageSize(size);
        save(byBranchName);
    }

    @Override
    public void createBranch(String os, String brandName, String branchDetail) {
        PatchBranch patchBranch = new PatchBranch();
        patchBranch.setCreateDate(LocalDateTime.now());
        patchBranch.setOs(os);
        patchBranch.setBranchName(brandName);
        patchBranch.setBranchDetail(branchDetail);
        save(patchBranch);
    }

    @Override
    public PatchBranch findByBranchName(String branchName) {
        return patchBranchDao.findByBranchName(branchName);
    }

    private Map<String, String> findSelect(){
        Map<String, String> map = Maps.newHashMap();
        for (PatchBranch patchBranch : patchBranchDao.findAll()) {
            map.put(patchBranch.getBranchName(), patchBranch.getBranchName());
        }
        return map;
    }

    @Override
    public Map<String, Select> getConfig() {
        Map<String, Select> map = Maps.newHashMap();
        map.put(SELECT_APP_PATCH_BRANCH, key -> findSelect());
        return map;
    }
}
