package com.realnet.Workspaceuser.Controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.realnet.Communication.Services.EmailNotificationService;
import com.realnet.Workspaceuser.Entity.Sec_team_members;
import com.realnet.Workspaceuser.Entity.Sec_workspace_users;
import com.realnet.Workspaceuser.Repository.SecWorkspaceUserRepo;
import com.realnet.Workspaceuser.Repository.Sec_team_MemberRepository;

import com.realnet.users.entity.Role;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.repository.RoleRepo;
import com.realnet.users.repository1.AppUserRepository;
import com.realnet.users.response.MessageResponse;
import com.realnet.users.service1.AppUserServiceImpl;

@RestController
@RequestMapping("/workspace/secworkspaceuser")
@EnableCaching
public class SecWorkSpaceUSerController {

	@Autowired
	private SecWorkspaceUserRepo secWorkspaceUserRepo;
	@Autowired
	private AppUserServiceImpl userService;
	

	@Autowired
	private Sec_team_MemberRepository memberRepository;
	@Autowired
	private AppUserRepository userRepository;

	@Autowired
	private RoleRepo roleRepo;

	@Autowired
	private EmailNotificationService emailNotificationService;



	// ADD WHOLE TEAM TO SECWORKSPACE USER BY TEAM_ID
	@PostMapping("/addteam/{project_id}/{team_id}")
	public ResponseEntity<?> addwholeteam(@PathVariable Integer project_id, @PathVariable int team_id,
			@RequestBody Sec_workspace_users users) {
		List<Object> list = new ArrayList<>();
		List<Sec_team_members> members = memberRepository.getallteam(team_id);
		for (Sec_team_members mem : members) {
			Sec_workspace_users secuser = secWorkspaceUserRepo.getallsecworkspcceuser(mem.getMember_id(), project_id);
			if (secuser == null) {
				Sec_workspace_users user = new Sec_workspace_users();
				Optional<AppUser> us = userRepository.findById(mem.getMember_id());
				user.setAccountId(us.get().getAccount().getAccount_id());
				user.setUser_id(mem.getMember_id());
				user.setWorksapce_id(project_id);
				user.setProject_id(project_id);
				user.setUser_name(mem.getMember_name());
//				        Set<Role> roles = new HashSet<>();
//				        String role1 = "ROLE_Developer";
//				        Role userRole = roleRepo.findByName(role1);
//				        roles.add(userRole);
//				        users.setUser_role(roles);
				Sec_workspace_users save = secWorkspaceUserRepo.save(user);

				list.add(save);

//				send mail to team member
				try {
					emailNotificationService.sendmailViaSetu(us.get().getEmail(), us.get().getFullName(), "TeamMember");

				} catch (Exception e) {
					System.out.println("email sending error ..." + e);
					// TODO: handle exception
				}

			}
		}
		return new ResponseEntity<>(list, HttpStatus.OK);
	}

	// GET ALL SEC_WORKSPACE_USER
	@GetMapping("/sec_workspace_users")
	public ResponseEntity<?> getallusers() {
		List<Sec_workspace_users> list = secWorkspaceUserRepo.findAll();
		return new ResponseEntity<>(list, HttpStatus.OK);
	}

	// GET ALL SEC_WORKSPACE_USER by PROJECT ID
	@GetMapping("/get_by_projectid/{project_id}")
	public ResponseEntity<?> getallusers(@PathVariable Integer project_id) {
		List<Sec_workspace_users> list = secWorkspaceUserRepo.getallproject(project_id);
		return new ResponseEntity<>(list, HttpStatus.OK);
	}

	// ADD SEC WORKSPACE USER
	@PostMapping("/add_workspace/users/{userid}/{project_id}/{access_duration}")
	public ResponseEntity<?> addsecusers(@RequestBody Sec_workspace_users users, @PathVariable Long userid,
			@PathVariable Integer project_id, @PathVariable Integer access_duration, @RequestParam String role) {

		AppUser loggedInUser = userService.getLoggedInUser();
		Long fromuserid = loggedInUser.getUserId();
		// Long account_id = loggedInUser.getAccount().getAccount_id();

		Sec_workspace_users workspace_users = secWorkspaceUserRepo.getallsecworkspcceuser(userid, project_id);
		if (workspace_users == null) {
			Optional<AppUser> us = userRepository.findById(userid);
			users.setAccountId(us.get().getAccount().getAccount_id());
			users.setFromuserId(fromuserid);
			users.setUser_id(userid);
			users.setUser_name(us.get().getFullName());
			users.setWorksapce_id(project_id);
			users.setProject_id(project_id);

			users.setAccess_duration(access_duration);

			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DATE, access_duration);

//			SimpleDateFormat dateFormat = new SimpleDateFormat();
//			String format = dateFormat.format(c.getTime());

			users.setAccess_till_date(c.getTime());

			Set<Role> roles = new HashSet<>();
//			String role1 = "ROLE_Developer";
			Role userRole = roleRepo.findByName(role);
//			roles.add(userRole);
			if (userRole != null) {
				users.setUser_role(role);
			}

			Sec_workspace_users save = secWorkspaceUserRepo.save(users);

//			send mail to team member

			try {

				emailNotificationService.sendmailViaSetu(us.get().getEmail(), us.get().getFullName(), "WorkSpaceUser");

			} catch (Exception e) {
				System.out.println("email sending error ..." + e);
				// TODO: handle exception
			}
			return new ResponseEntity<>(save, HttpStatus.OK);
		} else
			return ResponseEntity.badRequest().body(new MessageResponse("user already added"));

	}

}
