package org.cmh.backend.OrganizationManagement.controller;

import org.cmh.backend.OrganizationManagement.model.Organization;
import org.cmh.backend.OrganizationManagement.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.springframework.http.ResponseEntity.ok;

@RestController
@RequestMapping("/organizations")
public class OrganizationController {
    @Autowired
    private OrganizationService organizationService;

    @GetMapping("/listAll")
    public ResponseEntity<List<Organization>> listAll() {
        List<Organization> data = organizationService.listAll();
//        System.out.println(data);
        return ok(data);
    }

    @PostMapping("/addOrganization")
    public Organization add(@RequestBody Map<String, String> credentials) {
        Organization organization = new Organization();
        if (credentials.get("organizationId") != null) {
            organization.setOrganizationId(Long.parseLong(credentials.get("organizationId")));
        }
        organization.setOrganizationName(credentials.get("organizationName"));
        organization.setOrganizationStatus(Boolean.parseBoolean(credentials.get("organizationStatus")));
        if (Integer.parseInt(credentials.get("parentOrganization")) != 0) {
            organization.setParentOrganization(organizationService.getById(Long.parseLong(credentials.get("parentOrganization"))));
        } else {
            organization.setParentOrganization(null);
        }
        organization.setEmail(credentials.get("email"));
        organization.setLeader(credentials.get("leader"));
        organization.setContactPhone(credentials.get("contactPhone"));
        organization.setDisplayOrder(Integer.parseInt(credentials.get("displayOrder")));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentTime = sdf.format(new Date());
        System.out.println(currentTime);

        organization.setCreatedTime(currentTime);
        Organization organizationAdd = organizationService.add(organization);
        System.out.println(organizationAdd);
        return organizationAdd;
    }


    @PostMapping("/deleteOrganization")
    public String delete(@RequestBody Map<String, String> credentials) {
        organizationService.delete(Long.valueOf(credentials.get("organizationId")));
        return "success";
    }

    @PostMapping("/update")
    public Organization update(@RequestBody Organization organization) {
        return organizationService.update(organization);
    }

    @PostMapping("/getOrganizationById")
    public Organization getById(@RequestBody Map<String, String> credentials) {
        return organizationService.getById(Long.valueOf(credentials.get("organizationId")));
    }

    //ublic
}
