package com.dji.sample.wayline.controller;

import com.dji.sample.common.model.CustomClaim;
import com.dji.sample.manage.model.enums.OperateRecordTypeEnum;
import com.dji.sample.manage.service.IOperateRecordService;
import com.dji.sample.wayline.model.dto.TaskStatisticDTO;
import com.dji.sample.wayline.model.dto.TaskStatusStatisticDTO;
import com.dji.sample.wayline.model.dto.WaylineJobDTO;
import com.dji.sample.wayline.model.entity.WaylineJobEntity;
import com.dji.sample.wayline.model.param.CreateInFlightJobParam;
import com.dji.sample.wayline.model.param.CreateJobParam;
import com.dji.sample.wayline.model.param.UpdateJobParam;
import com.dji.sample.wayline.model.param.WaylineJobSearchParam;
import com.dji.sample.wayline.service.IFlightTaskService;
import com.dji.sample.wayline.service.IWaylineJobService;
import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.PaginationData;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import static com.dji.sample.component.AuthInterceptor.TOKEN_CLAIM;

/**
 * @author sean
 * @version 1.1
 * @date 2022/6/1
 */
@RequestMapping("${url.wayline.prefix}${url.wayline.version}/workspaces")
@RestController
public class WaylineJobController {

    @Autowired
    private IWaylineJobService waylineJobService;

    @Autowired
    private IFlightTaskService flighttaskService;

    @Autowired
    private IOperateRecordService operateRecordService;

    /**
     * Create a wayline task for the Dock.
     * @param request
     * @param param
     * @param workspaceId
     * @return
     * @throws SQLException
     */
    @PostMapping("/{workspace_id}/flight-tasks")
    public HttpResultResponse createJob(HttpServletRequest request, @Valid @RequestBody CreateJobParam param,
                                        @PathVariable(name = "workspace_id") String workspaceId) throws SQLException {
        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
        customClaim.setWorkspaceId(workspaceId);

        operateRecordService.record(request, OperateRecordTypeEnum.FLIGHT_TASK_CREATE, param.getDockSn(), param);

        return flighttaskService.publishFlightTask(param, customClaim);
    }

    /**
     * Paginate through all jobs in this workspace.
     * @param page
     * @param pageSize
     * @param workspaceId
     * @return
     */
    @GetMapping("/{workspace_id}/jobs")
    public HttpResultResponse<PaginationData<WaylineJobDTO>> getJobs(WaylineJobSearchParam param,
                                                                     @RequestParam(defaultValue = "1") Long page,
                                                                     @RequestParam(name = "page_size", defaultValue = "10") Long pageSize,
                                                                     @PathVariable(name = "workspace_id") String workspaceId) {
        PaginationData<WaylineJobDTO> data = waylineJobService.getJobsByParam(param, workspaceId, page, pageSize);
        return HttpResultResponse.success(data);
    }

    /**
     * Send the command to cancel the jobs.
     * @param jobIds
     * @param workspaceId
     * @return
     * @throws SQLException
     */
    @DeleteMapping("/{workspace_id}/jobs")
    public HttpResultResponse publishCancelJob(@RequestParam(name = "job_id") Set<String> jobIds,
                                               @PathVariable(name = "workspace_id") String workspaceId, HttpServletRequest request) throws SQLException {


        for(String jobId : jobIds) {

            operateRecordService.record(request, OperateRecordTypeEnum.FLIGHT_TASK_CANCEL, null,
                    java.util.Map.of("job_id", jobId));
        }


        flighttaskService.cancelFlightTask(workspaceId, jobIds);
        return HttpResultResponse.success();
    }

    /**
     * Set the media files for this job to upload immediately.
     * @param workspaceId
     * @param jobId
     * @return
     */
    @PostMapping("/{workspace_id}/jobs/{job_id}/media-highest")
    public HttpResultResponse uploadMediaHighestPriority(@PathVariable(name = "workspace_id") String workspaceId,
                                                         @PathVariable(name = "job_id") String jobId) {
        flighttaskService.uploadMediaHighestPriority(workspaceId, jobId);
        return HttpResultResponse.success();
    }

    @PutMapping("/{workspace_id}/jobs/{job_id}")
    public HttpResultResponse updateJobStatus(HttpServletRequest request,
                                              @PathVariable(name = "workspace_id") String workspaceId,
                                              @PathVariable(name = "job_id") String jobId,
                                              @Valid @RequestBody UpdateJobParam param) {

        flighttaskService.updateJobStatus(workspaceId, jobId, param);

        operateRecordService.record(request, OperateRecordTypeEnum.FLIGHT_TASK_UPDATE, null,
                java.util.Map.of("job_id", jobId, "param", param));

        return HttpResultResponse.success();
    }

    /**
     * 统计数据
     * @param workspaceId
     * @return
     */
    @GetMapping("/{workspace_id}/jobs/statistics")
    public HttpResultResponse<List<TaskStatisticDTO>> getTaskStatistics(@PathVariable(name = "workspace_id") String workspaceId,
                                                                              @RequestParam(name = "time_type", defaultValue = "0") Integer timeType) {
        List<TaskStatisticDTO> dto = waylineJobService.getTaskStatistics(workspaceId, timeType);
        return HttpResultResponse.success(dto);
    }

    /**
     * 今日任务
     * @param page
     * @param pageSize
     * @param workspaceId
     * @return
     */
    @GetMapping("/{workspace_id}/todayJobs")
    public HttpResultResponse<PaginationData<WaylineJobDTO>> getTodayJobs(@RequestParam(defaultValue = "1") Long page,
                                                                     @RequestParam(name = "page_size", defaultValue = "10") Long pageSize,
                                                                     @RequestParam(name = "dock_sns", required = false) String dockSns,
                                                                     @PathVariable(name = "workspace_id") String workspaceId) {
        PaginationData<WaylineJobDTO> data = waylineJobService.getTodayJobsByWorkspaceId(workspaceId, dockSns, page, pageSize);
        return HttpResultResponse.success(data);
    }

    /**
     * 导出任务
     * @param workspaceId
     * @return
     */
    @PostMapping("/{workspace_id}/export")
    public void export(HttpServletResponse response, @PathVariable(name = "workspace_id") String workspaceId) {

        waylineJobService.exportTaskList(response, workspaceId);
    }

    /**
     * 空中下发航线 in_flight_wayline_deliver
     */
    @PostMapping("/{workspace_id}/in-flight-tasks")
    public HttpResultResponse createInFlightJob(HttpServletRequest request, @Valid @RequestBody CreateInFlightJobParam param,
                                        @PathVariable(name = "workspace_id") String workspaceId) throws SQLException {
        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
        customClaim.setWorkspaceId(workspaceId);

        HttpResultResponse result = flighttaskService.publishInFlightTask(param, customClaim);

        operateRecordService.record(request, OperateRecordTypeEnum.IN_FLIGHT_TASK_CREATE, param.getDockSn(), param);

        return result;
    }

    /**
     * 暂停 或者 恢复 空中航线 in_flight_wayline_stop in_flight_wayline_recover
     */
    @PutMapping("/{workspace_id}/inFlightJobs/{job_id}")
    public HttpResultResponse updateInFlightJobStatus(@PathVariable(name = "workspace_id") String workspaceId,
                                              @PathVariable(name = "job_id") String jobId,
                                              @Valid @RequestBody UpdateJobParam param) {
        // todo
        // flighttaskService.updateJobStatus(workspaceId, jobId, param);
        return HttpResultResponse.success();
    }

    /**
     * 取消空中航线 in_flight_wayline_cancel
     */
    @DeleteMapping("/{workspace_id}/inFlightJobs")
    public HttpResultResponse publishCanceInFlightlJob(HttpServletRequest request,
                                                       @RequestParam(name = "dockeSn") String dockSn,
                                               @PathVariable(name = "workspace_id") String workspaceId) throws SQLException {
        flighttaskService.cancelInFlightTask(workspaceId, dockSn);

        operateRecordService.record(request, OperateRecordTypeEnum.IN_FLIGHT_TASK_CANCEL, dockSn, null);

        return HttpResultResponse.success();
    }

    /**
     * 统计任务状态
     */
    @GetMapping("/{workspace_id}/taskStatusCount")
    public HttpResultResponse getTaskStatusCount(@PathVariable(name = "workspace_id") String workspaceId) {
        List<TaskStatusStatisticDTO> taskStatusCount = waylineJobService.getTaskStatusCount(workspaceId);
        return HttpResultResponse.success(taskStatusCount);
    }

}
