/**
 * This file Copyright (c) 2009 Magnolia International
 * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
 *
 *
 * This program and the accompanying materials are made
 * available under the terms of the Magnolia Network Agreement
 * which accompanies this distribution, and is available at
 * http://www.magnolia-cms.com/mna.html
 *
 * Any modifications to this file must keep this entire header
 * intact.
 *
 */
package info.magnolia.project.someproject.productsearch.importer;

import info.magnolia.cms.core.Content;
import info.magnolia.cms.util.NodeDataUtil;
import info.magnolia.module.data.importer.ImportException;
import info.magnolia.module.data.importer.ImportHandler;
import info.magnolia.module.data.importer.ImportTarget;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Imports all categories from a csv file in format: cat_id, cat_name,depth, parent_cat_id. If the depth is 0, the cat_id have to be same as the parent_cat_id.
 * @author had
 *
 *  * @version $Revision: $ ($Author: $)
 */
public class CategoryImportHandler extends ImportHandler {

    /**
     * Logger
     */
    private Logger log = LoggerFactory.getLogger(getClass());
    private String importFileLocation;

    protected Set doImport(ImportTarget target, Content parent, Set uuids) throws ImportException {

        log.info("importing new data node");
        FileReader fileReader = null;
        BufferedReader dataReader = null;
        int lineCount = 0;
        try {
            fileReader = new FileReader(getImportFileLocation());
            dataReader = new BufferedReader(fileReader);
            String line = null;
            while ((line = dataReader.readLine()) != null) {
                lineCount++;
                String[] values = line.split(",");
                int id = -1;
                try {
                    id = Integer.parseInt(values[0]);
                } catch (NumberFormatException e) {
                    // NAN (e.g. header line) ... skip
                    continue;
                }
                // create new data node.
                // FYI: if the name matches existing node and "deleteExisting" is
                // set to true, old copy of the node will be automatically deleted.
                Content child = parent.createContent("" + id, "ProductCategory");
                // name of the node and the name property has to be in sync ...
                NodeDataUtil.getOrCreate(child, "name").setValue(id);
                if (values.length == 4) {
                    NodeDataUtil.getOrCreate(child, "TITLE").setValue(values[1].trim());
                } else {
                    // TODO: more then 1 category name ... for now just concatenate
                    StringBuilder sb = new StringBuilder();
                    for (int i = 1; i < values.length - 3; i++) {
                        if (i > 1) {
                            sb.append(",");
                        }
                        sb.append(values[i].trim());
                    }
                    NodeDataUtil.getOrCreate(child, "TITLE").setValue(sb.toString());

                }
                NodeDataUtil.getOrCreate(child, "CAT_ID").setValue(id);
                int depth = Integer.parseInt(values[values.length - 2]);
                if (depth != 0) {
                    NodeDataUtil.getOrCreate(child, "PARENT_CAT_ID").setValue(Integer.parseInt(values[values.length - 1]));
                    NodeDataUtil.getOrCreate(child, "DEPTH").setValue(depth);
                }
                // call parent save after each node creation to flush the session store otherwise we need more memory and saving will be slower at the end
                parent.save();
                uuids.add(child.getUUID());
            }
        }
        catch (Exception e) {
            log.error("Failed to import categories. Error at line " + lineCount, e);
        } finally {
            IOUtils.closeQuietly(dataReader);
            IOUtils.closeQuietly(fileReader);
        }
        log.info("Finished category import. Parsed {} lines of the {} file. {} ", lineCount, getImportFileLocation());
        return uuids;
    }

    private String getImportFileLocation() {
        return this.importFileLocation;
    }

    public void setImportFileLocation(String importFileLocation) {
        this.importFileLocation = importFileLocation;
    }

}