/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. licenses this file to you under the Apache License,
 *   Version 2.0 (the "License"); you may not use this file except
 *   in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */

package org.wso2.carbon.mss.examples.petstore.util.fe.view;

import de.larmic.butterfaces.event.TableSingleSelectionListener;
import de.larmic.butterfaces.model.table.DefaultTableModel;
import de.larmic.butterfaces.model.table.TableModel;
import org.wso2.carbon.mss.examples.petstore.util.fe.dao.PetService;
import org.wso2.carbon.mss.examples.petstore.util.fe.model.Configuration;
import org.wso2.carbon.mss.examples.petstore.util.fe.model.PetServiceException;
import org.wso2.carbon.mss.examples.petstore.util.model.Pet;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 * Bean classes used for JSF model.
 */
@ManagedBean
@RequestScoped
public class PetListBean {

    private static final Logger LOGGER = Logger.getLogger(PetListBean.class.getName());

    @Nullable
    @ManagedProperty("#{petService}")
    private PetService petService;
    private List<Pet> pets;
    private TableModel tableModel = new DefaultTableModel();
    private Pet selectedValue;

    @Nullable
    @ManagedProperty("#{configuration}")
    private Configuration configuration;

    @PostConstruct
    public void init() {
        pets = petService.listPets();
    }

    public PetService getPetService() {
        return petService;
    }

    public void setPetService(PetService petService) {
        this.petService = petService;
    }

    public TableModel getTableModel() {
        return tableModel;
    }

    public void setTableModel(TableModel tableModel) {
        this.tableModel = tableModel;
    }

    public List<Pet> getPets() {
        return pets;
    }

    public void setPets(List<Pet> pets) {
        this.pets = pets;
    }

    public void removePet(String id) throws PetServiceException {
        petService.remove(id);
        pets = petService.listPets();
    }

    public Pet getSelectedValue() {
        return selectedValue;
    }

    public void setSelectedValue(Pet selectedValue) {
        this.selectedValue = modifyImageURL(selectedValue);
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public TableSingleSelectionListener<Pet> getTableSelectionListener() {
        return new TableSingleSelectionListener<Pet>() {
            @Override
            public void processTableSelection(Pet data) {
                selectedValue = data;
            }

            @Override
            public boolean isValueSelected(Pet data) {
                return selectedValue != null ? data.getId().equals(selectedValue.getId()) : false;
            }
        };
    }


    public String backtoList() {
        return "list";
    }

    private String getServerIP() {
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) extContext.getRequest();
        LOGGER.info("================ printing all headers =============");
        for (String key : Collections.list(request.getHeaderNames())) {
            LOGGER.info(key + "=" + request.getHeader(key));
        }
        LOGGER.info("===================================================");
        String host = request.getHeader("host");
        if (host == null || host.isEmpty()) {
            host = request.getHeader("origin");
        }
        return host.substring(0, host.indexOf(":"));
    }

    private Pet modifyImageURL(Pet selectedValue) {
        getServerIP();
        LOGGER.info("Current Image URL " + selectedValue.getImage());
        try {
            Integer nodePort = Integer.valueOf(configuration.getFileUploadServiceNodePort());
            URL currentURL = new URL(selectedValue.getImage());
            String imageFile = currentURL.getFile();
            imageFile = "/fs/".concat(imageFile.substring(imageFile.lastIndexOf("/") + 1));
            URL newURL = new URL(currentURL.getProtocol(), getServerIP(), nodePort, imageFile);
            selectedValue.setImage(newURL.toString());
        } catch (MalformedURLException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }

        LOGGER.info("New Image URL " + selectedValue.getImage());
        return selectedValue;
    }
}

@@ -4052,24 +4052,86 @@
 tRequest();%0A
+        //TODO - Remove following log messages after testing.%0A
         LOGG
@@ -4895,201 +4895,64 @@
     
-URL currentURL = new URL(selectedValue.getImage());%0A            String imageFile = currentURL.getFile();%0A            imageFile = %22/fs/%22.concat(imageFile.substring(imageFile.lastIndexOf(%22/%22) + 1
+String imageFile = %22/fs/%22.concat(selectedValue.getImage(
 ));%0A
@@ -4988,32 +4988,14 @@
 URL(
-currentURL.getProtocol()
+%22http%22
 , ge

Change FE image source according to ImageService changes