package com.eactive.eai.rms.onl.manage.authserver.scope;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.eactive.eai.agent.authserver.ReloadApiScopeCommand;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeSearch;

@Controller
public class ScopeController extends OnlBaseAnnotationController {

	private ScopeManService scopeManService;

	@Autowired
	public ScopeController(ScopeManService scopeManService) {
		this.scopeManService = scopeManService;
	}

	@GetMapping(value = "/onl/admin/authserver/scopeMan.view")
	public void view() {
		// view
	}

	@GetMapping(value = "/onl/admin/authserver/scopeMan.view", params = "cmd=DETAIL")
	public String viewList() {
		return "/onl/admin/authserver/scopeManDetail";
	}

	@PostMapping(value = "/onl/admin/authserver/scopeMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<ScopeUI>> selectList(@SortDefault("scopeName") Pageable pageable, ScopeSearch scopeSearch) {
		Page<ScopeUI> page = scopeManService.selectList(pageable, scopeSearch);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value = "/onl/admin/authserver/scopeMan.json", params = "cmd=DETAIL")
	public ResponseEntity<ScopeUI> selectDetail(String scopeId) {
		ScopeUI scopeUI = scopeManService.selectDetail(scopeId);
		return ResponseEntity.ok(scopeUI);
	}

	@PostMapping(value = "/onl/admin/authserver/scopeMan.json", params = "cmd=INSERT")
	public ResponseEntity<Void> insert(ScopeUI scopeUI) {
		scopeManService.insert(scopeUI);
		return ResponseEntity.ok().build();
	}

	@PostMapping(value = "/onl/admin/authserver/scopeMan.json", params = "cmd=UPDATE")
	public ResponseEntity<Void> update(ScopeUI scopeUI) {
		scopeManService.update(scopeUI);
		return ResponseEntity.ok().build();
	}

	@PostMapping(value = "/onl/admin/authserver/scopeMan.json", params = "cmd=DELETE")
	public ResponseEntity<Void> delete(String scopeId) {
		scopeManService.delete(scopeId);
		scopeManService.deleteApiScopeRelationsByScopeId(scopeId);

		CommonCommand.builder()
								.name(CommonCommand.RELOAD_API_SCOPE_COMMAND)
								.args(new String[] {ReloadApiScopeCommand.COMMAND_TYPE_SCOPE, "", scopeId})
								.build()
								.broadcast(agentUtilService);
		
		return ResponseEntity.ok().build();
	}
	
}