/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.csu.sdmx.web.controllers;

import cz.csu.sdmx.validation.model.dsds.DsdFactory;
import cz.csu.sdmx.constants.JSP;
import cz.csu.sdmx.constants.SESSION;
import cz.csu.sdmx.constants.URL;
import cz.csu.sdmx.web.forms.DetectDsdForm;
import cz.csu.sdmx.web.validators.DetectDsdFormValidator;
import cz.csu.sdmx.validation.model.ValidationResult;
import cz.csu.sdmx.validation.model.dsds.Dsd;
import cz.csu.sdmx.validation.xml.XmlValidator;
import cz.csu.sdmx.web.security.User;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;

/**
 *
 * @author themi
 */
@Controller
public class DsdController extends BaseController{
    
    @Autowired
    private DetectDsdFormValidator formValidator;
    
    @InitBinder("detectDSDForm")
    public void dataBinding(WebDataBinder binder) {
        binder.addValidators(formValidator);
    }
    
    @RequestMapping(value = URL.DSD_DETECT)
    public String detectDsd(Model model) {
        if(session.getAttribute(SESSION.DSD) != null)
            return URL.redirectTo(URL.CONDITION_ADD);
        
        model.addAttribute(new DetectDsdForm());
        return JSP.DSD_DETECT;
    }  
    
    @RequestMapping(value = URL.DSD_DETECT_SUBMIT, method = RequestMethod.POST)
        public String detectDsdSubmit(@ModelAttribute @Validated DetectDsdForm form,BindingResult result, Model model) {
        if(result.hasErrors())
            return JSP.DSD_DETECT;
        
        MultipartFile dsdFile = form.getDsdFile();
        InputStream dsdStream;
        try {
            dsdStream = dsdFile.getInputStream();
        } catch (IOException ex) {
            result.addError(new ObjectError("DSDFile", "Unreadable file."));
            result.addError(new ObjectError("DSDFile", ex.getMessage()));
            return JSP.DSD_DETECT;
        }
        
        ValidationResult validationResult = new ValidationResult();
        Document dsdDoc = XmlValidator.validate(dsdFile.getOriginalFilename(), dsdStream, validationResult);
        if(validationResult.hasErrors()){
            model.addAttribute(validationResult);
            return JSP.DSD_DETECT;
        }
        
        Dsd dsd = DsdFactory.get(dsdDoc);
        if (dsd == null) {
            result.addError(new ObjectError("DSDFile", "Unsuported DSD data format."));
            return JSP.DSD_DETECT;
        }
        
        User currentUser = getCurrentUser();
        if(!currentUser.hasUrn(dsd.getURN())){
            result.addError(new ObjectError("DSDFile", "You do not have any permission to add condition to urn: " + dsd.getURN()));
            return JSP.DSD_DETECT;
        }
        
        session.setAttribute(SESSION.DSD, dsd);
        return URL.redirectTo(URL.CONDITION_ADD);        
    }   
    
    @RequestMapping(value = URL.DSD_CLEAR, method = RequestMethod.POST)
    public String clearDSD() {
        session.removeAttribute(SESSION.DSD);
        return URL.redirectTo(URL.DSD_DETECT);
    } 
}
