<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="sapphire.servicedesk.utils.*" %>
<%
    IConfigSettingService configSettingService = (IConfigSettingService) SpringContextUtil.getBeanByName("configSettingService",Sapphire.applicationScope);
    String telantName2= (String)session.getAttribute("TELANTNAME");
if(new Sapphire().checkModuleAccess((String)session.getAttribute("login"),"Settings",telantName2) == 0){
%>
<jsp:forward page="login_page.htm"></jsp:forward>
<%} %>
<%@ include file="SapphireStdIncludes.jsp" %>
<%@include file="AJAXPopup.jsp" %>
<%@ include file="SapphireStdCSS.jsp" %>
<%@ include file="SapphireStdJs.jsp" %>
<%@ include file="clearCache.jsp" %>
<%@ include file="toptable.jsp" %>
<%@include file="EXTJSIncludes-4.jsp" %>

<%@ page import="org.owasp.encoder.Encode" %>
<%@page import="org.xnap.commons.i18n.I18n"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<script type ="text/javascript" src="js/AssetLeftSettings.js"></script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<%
    I18n i18n = Sapphire.LANGUAGE_MAP.get((String) session.getAttribute("LANGUAGE_UNICODE"));
    String messageIn =""; 
    String messageIn1 =""; 

%>
<script type="text/javascript">
var cc=0;
function chk2()
{

 var field1=document.form1.headerChk;


 var aa=document.form1.check;

 var i=0;
 if(field1.checked==true)
 {

    for(i=0;i<aa.length;i++)
    {
      if(aa[i].checked==false)
      {

           aa[i].checked=true;
            cc++;
           }
       }

 document.form1.chkcount.value=cc;
 return;
 }


 if(field1.checked==false)
 {
 for(i=0;i<aa.length;i++)
 {
    aa[i].checked=false;

    cc--;
 }
 document.form1.chkcount.value=cc;
 return;
 }

 }	
    function deleteShow(){
		var relationships=document.form1.check;
		var checkFlag=0;                
		if(relationships.length==undefined){
			if(relationships.checked){
                                <% messageIn = i18n.tr("Do you want to delete the selected relationship(s) ?");%>
				var confirmStatus=confirm("<%= messageIn%>");
				if(confirmStatus==false){
					return;
				}
			}else{
                                <% messageIn = i18n.tr("Please select at least one relationship to delete");%>
                                alert("<%= messageIn%>");
				return;
			}

		}else{
			for(var i=0;i<relationships.length;i++){
				if(relationships[i].checked){
					checkFlag=1;
					break;
				}
			}
			if(checkFlag==1){
                                <% messageIn = i18n.tr("Do you want to delete the selected relationship(s)?");%>
                                <%if(session.getAttribute("SERVICEDESK_NEWUI_PAGE")== null){%>
                                var confirmStatus=confirm("<%= messageIn%>");
                                <%}else{%>
                                    getValueFromCustomConfirm("<%= messageIn%>").then(result => {
                                        confirmStatus=result;
                                <%}%>
				if(confirmStatus==false){
					return;
				}
                <%if(session.getAttribute("SERVICEDESK_NEWUI_PAGE")!= null){%>
                        document.form1.submit();
                    });
                <%}%>
			}else{
                                <% messageIn = i18n.tr("Please select at least one relationship to delete");%>
                                alert("<%= messageIn%>");
				return;
			}
		}
        <%if(session.getAttribute("SERVICEDESK_NEWUI_PAGE")== null){%>
		document.form1.submit();
        <%}%>
	}
	
	function removeJerk(){
		document.getElementById("modelDescription").innerHTML="";
                changeFunction();
	}
       
        function reloadPage(){
            var moduleId = encodeURIComponent(document.getElementById('moduleId').value);
            window.location.href="RelationshipConfig_List.jsp?module=AssetRelation&moduleId="+moduleId+"&isNewUIAvailable=yes";
        }
        function auditLogDetails()
        {
            var moduleId = encodeURIComponent(document.getElementById('moduleId').value);
            var url="Asset_History.jsp?moduleID=19&type=outside&moduletype="+moduleId+"&isNewUIPopupAvailable=yes";
            popUpPage(url,800,300,'&nbsp;');
        }


        
</script>

</head>
<body onload="removeJerk()">

<div id="mainContentArea1" class="assetMainFrame">
<form name="form1" id="form1" method="post" action="RelationshipConfiguration?actionRequeried=delete">
<security:csrfInput/>
<%
    String moduleId = "1";
    if(request.getParameter("moduleId")!=null)
        moduleId = request.getParameter("moduleId"); 
%>
  <table width="100%" border="0" height="70%" cellspacing="0" cellpadding="0" class="" >
         <tr>
           <td width="9%" id="settingstd" valign="top" >
                            <jsp:include page="AssetSettingsLeftSideMenu.jsp">
                            <jsp:param name="module" value="AssetRelation" />
                            <jsp:param name="assetModuleId" value="<%=moduleId%>" />
                            </jsp:include>
                            <input type="hidden" name="frmPagination" id="frmPagination" value="1" />
                <div class="widgetBlock" id="settingscollapsediv" style="display:none"> <% messageIn = i18n.tr("Expand Asset Settings");%>
                    <img style="cursor:pointer;" src="updatedImages/widget_expand_right.png" title="<%= messageIn%>" onclick="showSettings()" />
                </div>
            </td>
<%
            connection myConn = null;
            Connection conn   = null;
            PreparedStatement pstmt  = null;
            ResultSet rs      = null;
            String RelationId   = null;
            String RelationName = null;
            String Description = null;
            String ItemTypeName    = null;
            String fRelation    = null;
            String iRelation    = null;
            Vector vector=null;
            
	   
	    try{	
                    myConn = new connection();
                    conn = myConn.getConnection(telantName2);
                    vector = new Vector();
                    String listCondition=" moduleid in(0,?) and ";
                    int preShippedRelationEnabled = (NumberUtils.toInt(configSettingService.findBySettingKey("ASSET_RELATION_PRESHIPPED")));
                    if(preShippedRelationEnabled == 0){
                      listCondition=" moduleid =? and ";
                    }
                    pstmt = conn.prepareStatement("select id,  Relationshipname, ci.Description,if(ci.itemtypeid=0,'Default',(select itemtype from assetitemtype_master where itemtypeid=ci.itemtypeid)) , fRelationshiptype, iRelationshiptype from ci_relationship_master ci where "+listCondition+" isdeleted=0 order by Relationshipname");
                    pstmt.setInt(1, Integer.parseInt(moduleId));
                    rs=pstmt.executeQuery();
                    while(rs.next())
                    {
                        RelationId=rs.getString(1);
                        RelationName=rs.getString(2);
                        Description=rs.getString(3);
                        ItemTypeName = rs.getString(4);
                        fRelation=rs.getString(5);
                        iRelation=rs.getString(6);
                        
                        DomainsVector form=new DomainsVector(RelationId,RelationName,Description,ItemTypeName,"<input type=\"checkbox\" id=\"check\" name=\"check\" value="+RelationId+" class=\"gen\" onclick=\"dis()\">",fRelation,iRelation);
                        vector.add(form);					     
                    }rs.close();pstmt.close();			
                    session.setAttribute("ASSETRELATION",vector);
                    
                    String Columns=i18n.tr("Relation Name")+","+i18n.tr("Description")+","+i18n.tr("Forward Relation")+","+i18n.tr("Inverse Relation")+","+i18n.tr("Item Type"); 
                    String[] selectedColumnNames = Columns.split(",");
                    String[] userdataColumns={"SNo","domainName","title","id","id1","who"};    
                    String exportColumns="";              
                    if(!selectedColumnNames[0].trim().equalsIgnoreCase("")){                
                       for(int i=0;i<selectedColumnNames.length;i++){            
                           if(exportColumns == ""){                
                               exportColumns=selectedColumnNames[i]+"_"+userdataColumns[i+1];                                   
                           }else{                
                               exportColumns+=","+selectedColumnNames[i]+"_"+userdataColumns[i+1];                 
                           }

                       }
                    }
                    session.setAttribute("ASSETRELATIONCOLUMNNAMES", exportColumns); 
			
	        }catch(Exception e)
	        {
	                logger.error("In RelationshipConfig_List.jsp ::"+ e.getMessage());
                        StackTraceElement[] stackTrace = null;
                            stackTrace = e.getStackTrace();
                            for (int i = 0; i < stackTrace.length; i++) {
                            logger.error("---- "+ stackTrace[i].toString());
                         }
	        }
	        finally
	        {
	         try{
                     if(pstmt!=null)
                       pstmt.close();
	             if(conn!=null)
	               conn.close();
	        
                 }catch(Exception e2){
                    logger.error("In finally catch of RelationshipConfig_List.jsp ::"+ e2.getMessage());
                    StackTraceElement[] stackTrace = null;
                        stackTrace = e2.getStackTrace();
                        for (int i = 0; i < stackTrace.length; i++) {
                        logger.error("---- "+ stackTrace[i].toString());
                     }
	        }
	     }            
%>            
            <td valign="top">
                <div class="widgetBlock"> 
                    <div class="widgetHeader auditlogposition"><h2><%= i18n.tr("Relationship ")%>&nbsp</h2><span></span>
                         <img src="img/Audit_Log.png" title="Audit Log" border="0"  style="cursor: pointer;margin: 15px;margin-top: 4px;height: 18px;width: 18px;" class="newUIAuditLog" onclick="auditLogDetails();"></div>
                    <div class="widgetOuterWrapper"> 
                        <div class="widgetInnerWrapper"> 
                <table width="100%" class='' border="0" cellspacing="2" cellpadding="0">
                    <tr>
                        <td width='100%' class="wid100">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                
                                <tr>
                                  <td class="wid100">
                                      <table width="100%">
                                          <tr>
                                              <td align="left">
                                                  <a class="addbuttons greenBtn" href="RelationshipConfig_Add.jsp?actionType=add&moduleId=<%= Encode.forUriComponent(moduleId) %>&isNewUIAvailable=yes"><%= i18n.tr("ADD")%></a>
                                                    <a onclick="deleteShow()" href="#" class="addbuttons"><%= i18n.tr("DELETE")%></a> 
                                              </td>
                                              <td align="right" class="floatRightAsset negativeMargin">
                                                
                                                  <select id="moduleId" name="moduleId" onchange="reloadPage()"><%
                                                          
                                                            Map assetModuleList = new Sapphire().getAssetModuleNames("0",telantName2); 
                                                            String assetModuleId="1";
                                                            String assetModuleName="Asset";

                                                            Set s = assetModuleList.entrySet();
                                                              Iterator itr = s.iterator();
                                                              while(itr.hasNext()){
                                                                  Map.Entry mEntry = (Map.Entry)itr.next();
                                                                 assetModuleId=(String)(mEntry.getKey() );
                                                                 assetModuleName=(String)(mEntry.getValue() ); %>
                                                                 <%if(assetModuleId.equals(moduleId)){%>
                                                                 <option value="<%=assetModuleId%>" selected><%=assetModuleName%></option>
                                                            <%  }  else{  %>
                                                            <option value="<%=assetModuleId%>"><%=assetModuleName%></option>
                                                            <%}}%>
                                                      
                                                 </select>
                                                
                                                    <%=Sapphire.getPaginationSelectedList( session ,"removeJerk()") %>
                                                   
                                                    <input type="hidden" value="delete" id="actionrequired" name="actionrequired" />
                                             </td>
                                          </tr>
                                      </table>
                                  </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    
                    <tr>
                        <td width="100%">
                            <div class="bgTransp" id="modelDescription" style="width:100%">

                            </div>
                        </td>
                    </tr>
                    
                
<script type="text/javascript" >

Ext.Loader.setConfig({enabled: true});


Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.toolbar.Paging',
    
    'Ext.ModelManager',
    'Ext.tip.QuickTipManager'
]);
function changeFunction(){
     var count=document.getElementById('paginationrowcount').value;
    Ext.tip.QuickTipManager.init();

    Ext.define('modelData'+count, {
        extend: 'Ext.data.Model',
        fields: [
            'SNo', 'domainName', 'title','who','when','id','id1','id2',
        ],
        idProperty: 'threadid'
    });
    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        pageSize: count,
        model: 'modelData'+count,
        remoteSort: true,
        proxy: {
            type: 'ajax',
            url: 'JSONObject.jsp?sessionValue=ASSETRELATION',
            reader: {
                root: 'rows',
                totalProperty: 'total'
            },
            // sends single sort as multi parameter
            simpleSortMode: true
        },
        sorters: [{
            property: 'domainName',
            direction: 'DESC'
        }]
    });
    // pluggable renders
    function renderRelationshipName(value,p,record){
        if(record.data.who=="Default"){
             return Ext.String.format(
                '<span \'>{1}</a>',
                record.data.SNo,  record.data.domainName);
        }else{
            return Ext.String.format(
                '<span style="cursor:pointer" onclick=\'javascript:window.location.href="RelationshipConfig_Add.jsp?actionType=edit&moduleId=<%=moduleId%>&id={0}"+"&isNewUIAvailable=yes"\'>{1}</a>',
                record.data.SNo,  record.data.domainName); 
        }
       
    }
    function renderCheck(value, p, record){
        if(record.data.who=="Default"){
            return Ext.String.format(
                '<input type="checkbox" id="check" name="check" value="{0}" onclick=""/> <label class="checkCustGrid"></label>'
                );
        }else{
        return Ext.String.format(
                '<input type="checkbox" id="check" name="check" value="{0}" onclick=""/> <label class="checkCustGrid"></label>',
                record.data.SNo);
            }
        }    
    var pluginExpanded = true;
    var grid = Ext.create('Ext.grid.Panel', {
        id:'paginationgrid',
        width:screen.width-300,
        autoHeight: true,
        align:'center',
        title: '',
        store: store,
        baseCls:'commonGridWid x-panel',
        disableSelection: false,
        loadMask: true,
        columnLines: true,
        noCache: true,
        stateId: 'assetPrepostListGridStateID',        
        stateful: true,
        stateEvents: ["columnmove", "columnresize", "sortchange", "show", "hide"],
        viewConfig: {
            id: 'assetPrepostListGV',
            trackOver: true,
            stripeRows: true
            
        },
        
            columns:[{
	                 id: 'AssetRelation-check', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
	                 header: "<span class='x-grid-cell-inner'><input type='checkbox' name='headerChk' id='headerChk' onClick='chk2()' /> <label class='checkCustGrid headerCheckPos2'></label></span>",
	                 dataIndex: 'SNo',
	                 width:60,
	                 renderer: renderCheck,
                         align: 'center',
                         //hideable: false,
	                 sortable: false
	             },{<% messageIn = i18n.tr("Relation Name");%> 
                         id: 'AssetRelation-Name',
	                 header: "<%= messageIn%>",
                         dataIndex: 'domainName',
	                 renderer: renderRelationshipName,
	                 width:250,
                         align: 'left',
                         hideable: false,
	                 sortable: true
	             },
                     {<% messageIn = i18n.tr("Description");%> 
                         id: 'AssetRelation-Des',
	                 header: "<%= messageIn%>",
                         dataIndex: 'title',
	                 width:200,
                         flex: 1,
                         align: 'left',
                         hideable: false,
	                 sortable: true
	             },
                     {<% messageIn = i18n.tr("Forward Relation");%> 
                         id: 'ForwardRelation-Type',
	                 header: "<%= messageIn%>",
	                 dataIndex: 'id',
                         width:150,
                         flex: 1,	                 
	                 align: 'left',
	                 sortable: true
	             },
                     {<% messageIn = i18n.tr("Inverse Relation");%> 
                         id: 'InverseRelation-Type',
	                 header: "<%= messageIn%>",
	                 dataIndex: 'id1',
                         width:150,
                         flex: 1,	                 
	                 align: 'left',
	                 sortable: true
	             },
                     {<% messageIn = i18n.tr("Item Type");%> 
                         id: 'AssetRelation-Type',
	                 header: "<%= messageIn%>",
	                 dataIndex: 'who',
                         width:150,
                         flex: 1,	                 
	                 align: 'left',
	                 sortable: true
	             }
                 ],
        // paging bar on the bottom
        bbar: Ext.create('Ext.PagingToolbar', {
            store: store,
            items:[
                Ext.create('Ext.Button', {
                   <% messageIn = i18n.tr("Excel");%>
                    text:'<%= messageIn%>',
                        handler:function(){<% messageIn = i18n.tr("AssetRelationshipConfig");%>
                            exportToExcel("ASSETRELATION","<%= messageIn%>","ASSETRELATIONCOLUMNNAMES");
                        }
                    })
            ],
            displayInfo: true,
            <% messageIn = i18n.tr("Displaying Asset Relationships"); messageIn1 = i18n.tr("of");%>
            displayMsg: ' <%= messageIn%> {0} - {1} <%= messageIn1%> {2}',
            <% messageIn = i18n.tr("No Asset Relationships to display");%>
            emptyMsg: "<%= messageIn%>"
            
        }),
        renderTo: 'modelDescription'
    });
    // trigger the data store load
    store.loadPage(1);    
}								
</script>      	             
        
    </table>
         </div>
                <div class="widgetFooter"></div>
            </div>  
                </div>
</td>
                    </tr>
                </table>
            </td>
         </tr>
      </table>
    </form>
</div>

 <%@ include file="Sapphire_Footer.jsp" %>
</body>
</html>