import { ProjectAddService } from '../services/projectAddService.js'
import { sendError } from '../utils/response.js'
// import { OftenError } from '../utils/oftenError.js'
import { GeneralService } from '../share/generalservice.js';
import { trim_all_array } from '../utils/trim.js'
import { verifyToken, generateToken } from '../utils/token.js'
import { Interface } from '../interfaces/Interface.js';


export class projectAdd {

  constructor() {
    this.generalService = new GeneralService();
    this.Interface = new Interface();
    this.projectAddService = new ProjectAddService();
  }

  async onNavigate(req, res) {
    this.generalService.devhint(1, 'projectAdd.js', 'onNavigate() start');
    let organization = req.body.organization;
    const prommis = await this.onProjectAdd(req, res, organization);
    return prommis;
  }

  async onProjectAdd(req, res, database) {
    let idx = -1
    let aryResult = []
    let latSeq = []
    try {
      let token = req.headers.authorization?.split(' ')[1];
      const decoded = verifyToken(token);

      let name = req.body.request.prjnam;
      database = decoded.organization;

      aryResult = await this.projectAddService.getProjectAdd(database, name);
      latSeq = await this.projectAddService.getLatestProjectSeq(database);
      //   this.generalService.devhint(1, 'budgetSearch.js', 'Login success');
    } catch (error) {
      idx = 1;
    } finally {
      if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
      // if (!aryResult) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');

      if (aryResult == 0) {
        let prommis = await this.makeArySave(req, latSeq[0].prjseq);
        return prommis
      } else {
        return sendError('คีย์หลักซ้ำในระบบ', 'Duplicate Primary Key');
      }
    }
  }


  async makeArySave(req, latseq) {
    let arysave = {
      methods: 'post',
      prjseq: latseq+1,
      prjnam: req.body.request.prjnam,
      prjusrseq: req.body.request.prjusrseq,
      prjwntbdg: req.body.request.prjwntbdg,
      prjacpbdg: req.body.request.prjacpbdg,
      prjbdgcod: req.body.request.prjbdgcod,
      prjcomstt: req.body.request.prjcomstt,
      prjacpdtm: req.body.request.prjacpdtm
    }
    return this.Interface.saveInterface('prjmst', arysave, req);
  }
}
