package com.jty.wsxt.interfaces.controller;

import com.jty.wsxt.application.ApplicationRegistry;
import com.jty.wsxt.domain.model.auth.user.nrsc.NrscTeacher;
import com.jty.wsxt.infrastructure.security.MyUserDetail;
import com.jty.wsxt.infrastructure.support.BusinessException;
import com.jty.wsxt.infrastructure.support.Result;
import com.jty.wsxt.infrastructure.support.ResultCode;
import com.jty.wsxt.interfaces.Assembler;
import com.jty.wsxt.interfaces.dto.ChangePasswordDto;
import com.jty.wsxt.interfaces.dto.NrscTeacherDto;
import com.jty.wsxt.interfaces.dto.NrscTeacherSearchDto;
import com.jty.wsxt.interfaces.dto.OperatorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * NrscTeacherController
 *
 * @author Manjiajie
 * @since 2019-2-13 19:19:46
 */
@RestController
public class NrscTeacherController {
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public NrscTeacherController(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @PostMapping("/user")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result addNrscTeacher(@RequestBody @Valid NrscTeacherDto nrscTeacherDto){
        ApplicationRegistry.nrscTeacherService().saveNrscTeacher(nrscTeacherDto);
        return Result.success();
    }

    @PutMapping("/user/{userId}")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result updateTeacher(@PathVariable Integer userId, @RequestBody NrscTeacherDto nrscTeacherDto){
        nrscTeacherDto.setId(userId);
        ApplicationRegistry.nrscTeacherService().updateNrscTeacher(nrscTeacherDto);
        return Result.success();
    }

    @GetMapping("/users")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result getNrscTeachers(NrscTeacherSearchDto searchDto){
        Page<NrscTeacher> pageTeacher = ApplicationRegistry.nrscTeacherService().getNrscTeachers(searchDto);
        List<NrscTeacherDto> teacherDtoList = new ArrayList<>();
        if(pageTeacher.getTotalElements() != 0){
            pageTeacher.getContent().forEach(nrscTeacher -> teacherDtoList.add(Assembler.castToNrscTeacherDto(nrscTeacher)));
        }
        return Result.success(new PageImpl<>(teacherDtoList,pageTeacher.getPageable(),pageTeacher.getTotalElements()));
    }

    @PutMapping("/user/{userId}/enable")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result enablerNrscTeacher(@PathVariable Integer userId, @RequestBody OperatorDto operatorDto, @AuthenticationPrincipal MyUserDetail operator){
        operatorDto.setOperatorId(operator.getUserId());
        operatorDto.setOperatorName(operator.getRealName());
        ApplicationRegistry.nrscTeacherService().enableNrscTeacher(userId,operatorDto);
        return Result.success();
    }

    @PutMapping("/user/{userId}/disable")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result disableNrscTeacher(@PathVariable Integer userId, @RequestBody OperatorDto operatorDto, @AuthenticationPrincipal MyUserDetail operator){
        operatorDto.setOperatorId(operator.getUserId());
        operatorDto.setOperatorName(operator.getRealName());
        ApplicationRegistry.nrscTeacherService().disableNrscTeacher(userId,operatorDto);
        return Result.success();
    }

    @PutMapping("/user/{userId}/password/reset")
    @PreAuthorize("hasAuthority('NRSC_MANAGE_USER')")
    public Result resetPassword(@PathVariable Integer userId){
        return Result.success(ApplicationRegistry.nrscTeacherService().resetPassword(userId));
    }
    @PostMapping("/user/password/change")
    public Result changePassword(@RequestBody ChangePasswordDto changePasswordDTO, @AuthenticationPrincipal MyUserDetail userDetails){
        if(!passwordEncoder.matches(changePasswordDTO.getOldPassword(),userDetails.getPassword())){
            throw new BusinessException(ResultCode.PASSWORD_ERROR);
        }else if(passwordEncoder.matches(changePasswordDTO.getNewPassword(),(userDetails.getPassword()))){
            throw new BusinessException(ResultCode.PASSWORD_REPEATED);
        } else{
            ApplicationRegistry.nrscTeacherService().changePassword(changePasswordDTO.getNewPassword(),userDetails.getUserId());
        }

        return Result.success();
    }
}