package tutorial.rest.mvc;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestParam;
import tutorial.core.models.entities.EmailDomain;
import tutorial.core.services.AccountService;
import tutorial.core.services.EmailDomainService;
import tutorial.core.services.exceptions.AccountDoesNotExistException;
import tutorial.core.services.exceptions.EmailDomainExistsException;
import tutorial.core.services.util.EmailDomainList;
import tutorial.rest.exceptions.ConflictException;
import tutorial.rest.resources.EmailDomainListResource;
import tutorial.rest.resources.EmailDomainResource;
import tutorial.rest.resources.asm.EmailDomainListResourceAsm;
import tutorial.rest.resources.asm.EmailDomainResourceAsm;



/**
 * 
 * @author Xavier
 */
@Controller
@RequestMapping("/rest/emailDomain")
public class EmailDomainController {
    private EmailDomainService emailDomainService;
    private AccountService accountService;
    
    /**
     *
     * @param emailDomainService
     * @param accountService
     */
    @Autowired
    public EmailDomainController(EmailDomainService emailDomainService, AccountService accountService) {
        this.emailDomainService = emailDomainService;
        this.accountService = accountService;
    }

    /**
     * Adds one emailDomain to the database
     * @param payload the values that the created emailDomain will have
     * @return returns the created emailDomain
     */
    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("permitAll")
    public ResponseEntity<EmailDomainResource> createEmailDomain(
            @RequestBody EmailDomainResource payload)
    {
        try {
            EmailDomain createdEmailDomain = emailDomainService.createEmailDomain(payload);
            EmailDomainResource createdEmailDomainRes = new EmailDomainResourceAsm().toResource(createdEmailDomain);
            return new ResponseEntity<EmailDomainResource>(createdEmailDomainRes, HttpStatus.CREATED);
        } catch(AccountDoesNotExistException exception)
        {
            throw new ConflictException(exception);
        }
    }

    /**
     * Returns a List of all emailDomains
     * @return 
     */
    @RequestMapping(method = RequestMethod.GET)
    @PreAuthorize("permitAll")
    public ResponseEntity<EmailDomainListResource> findAllEmailDomains()
    {
        EmailDomainList emailDomainList = emailDomainService.findAllEmailDomains();
        EmailDomainListResource emailDomainListRes = new EmailDomainListResourceAsm().toResource(emailDomainList);
        return new ResponseEntity<EmailDomainListResource>(emailDomainListRes, HttpStatus.OK);
    }
    
    
    /**
     * Given the content of a csv file, creates all the emailDomains sent in the data.
     * @param payload the content of a csv file
     * @return returns HttpStatus.CONFLICT if there is an Error or HttpStatus.CREATED if there was no problem and everything was created
     */
    @RequestMapping(value="/excel",
    method = RequestMethod.POST)
    @PreAuthorize("permitAll")
    public ResponseEntity createEmailDomainFromExcel(
            @RequestBody String payload
    ) {
        if(!payload.contains("\n")){
            return new ResponseEntity<EmailDomainResource>(HttpStatus.CONFLICT);
        }
        String[] rows = payload.split("\n");
        for(int i = 1;i<rows.length;i++){
            try {
                EmailDomainResource res = new EmailDomainResource();
                res.setEmailDomainText(rows[i]);
                EmailDomain createdEmailDomain = emailDomainService.createEmailDomain(res);
                new EmailDomainResourceAsm().toResource(createdEmailDomain);
            } catch(EmailDomainExistsException e)
            {
                return new ResponseEntity<EmailDomainResource>(HttpStatus.CONFLICT);
            }
        }
        return new ResponseEntity<EmailDomainResource>(HttpStatus.CREATED);
    }
    
    /**
     * If the user and password are in the database, and the user is an administrator,
     * deletes all data from the emailDomain table
     * @param name user email
     * @param password user password in MD5
     * @return HttpStatus.CONFLICT if the password doesn't match, HttpStatus.OK if everything went OK
     */
    @RequestMapping(value="/clearTable",
    method = RequestMethod.POST)
    @PreAuthorize("permitAll")
    public ResponseEntity deleteAllEmailDomains(
            @RequestParam(value="name", required = true) String name,
            @RequestParam(value="password", required = true) String password) {
        if(!accountService.isAccountCorrect(name, password)) {
            return new ResponseEntity(HttpStatus.CONFLICT);
        }else{
            emailDomainService.deleteAllEmailDomains();
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}
