<commit_before>/*
Copyright 2017 WALLIX

Licensed 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 console

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"reflect"
	"sort"
	"strings"
	"time"

	"github.com/fatih/color"
	"github.com/olekukonko/tablewriter"
	"github.com/wallix/awless/cloud"
	"github.com/wallix/awless/graph"
)

var (
	tableColWidth   = 30
	autowrapMaxSize = 35
)

type Displayer interface {
	Print(io.Writer) error
}

type sorter interface {
	sort(table)
	columns() []int
}

type Builder struct {
	filters         []string
	tagFilters      []string
	tagKeyFilters   []string
	tagValueFilters []string
	headers         []ColumnDefinition
	format          string
	rdfType         string
	sort            []int
	maxwidth        int
	dataSource      interface{}
	root            *graph.Resource
}

func (b *Builder) SetSource(i interface{}) *Builder {
	b.dataSource = i
	return b
}

func (b *Builder) buildGraphFilters() (funcs []graph.FilterFn) {
	for _, f := range b.filters {
		splits := strings.SplitN(f, "=", 2)
		if len(splits) == 2 {
			name, val := strings.TrimSpace(strings.Title(splits[0])), strings.TrimSpace(splits[1])
			key := ColumnDefinitions(b.headers).resolveKey(name)

			if key != "" {
				funcs = append(funcs, graph.BuildPropertyFilterFunc(key, val))
			}
		}

	}
	return
}

func (b *Builder) buildGraphTagFilters() (funcs []graph.FilterFn) {
	for _, f := range b.tagFilters {
		splits := strings.SplitN(f, "=", 2)
		if len(splits) == 2 {
			key, val := strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1])
			funcs = append(funcs, graph.BuildTagFilterFunc(key, val))
		}
	}
	return
}

func (b *Builder) buildGraphTagKeyFilters() (funcs []graph.FilterFn) {
	for _, k := range b.tagKeyFilters {
		funcs = append(funcs, graph.BuildTagKeyFilterFunc(k))
	}
	return
}

func (b *Builder) buildGraphTagValueFilters() (funcs []graph.FilterFn) {
	for _, v := range b.tagValueFilters {
		funcs = append(funcs, graph.BuildTagValueFilterFunc(v))
	}
	return
}

func (b *Builder) Build() (Displayer, error) {
	base := fromGraphDisplayer{sorter: &defaultSorter{sortBy: b.sort}, rdfType: b.rdfType, headers: b.headers, maxwidth: b.maxwidth}

	switch b.dataSource.(type) {
	case *graph.Graph:
		gph := b.dataSource.(*graph.Graph)
		filteredGraph, err := gph.Filter(b.rdfType, b.buildGraphFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.OrFilter(b.rdfType, b.buildGraphTagFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.OrFilter(b.rdfType, b.buildGraphTagKeyFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.OrFilter(b.rdfType, b.buildGraphTagValueFilters()...)
		if err != nil {
			return nil, err
		}

		if b.rdfType == "" {
			switch b.format {
			case "table":
				dis := &multiResourcesTableDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			case "json":
				dis := &multiResourcesJSONDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			case "porcelain":
				dis := &porcelainDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			default:<commit_msg>Issue #97 - intersection on mulitple tag filering... ... same behaviour as AWS classic cli<commit_after>/*
Copyright 2017 WALLIX

Licensed 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 console

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"reflect"
	"sort"
	"strings"
	"time"

	"github.com/fatih/color"
	"github.com/olekukonko/tablewriter"
	"github.com/wallix/awless/cloud"
	"github.com/wallix/awless/graph"
)

var (
	tableColWidth   = 30
	autowrapMaxSize = 35
)

type Displayer interface {
	Print(io.Writer) error
}

type sorter interface {
	sort(table)
	columns() []int
}

type Builder struct {
	filters         []string
	tagFilters      []string
	tagKeyFilters   []string
	tagValueFilters []string
	headers         []ColumnDefinition
	format          string
	rdfType         string
	sort            []int
	maxwidth        int
	dataSource      interface{}
	root            *graph.Resource
}

func (b *Builder) SetSource(i interface{}) *Builder {
	b.dataSource = i
	return b
}

func (b *Builder) buildGraphFilters() (funcs []graph.FilterFn) {
	for _, f := range b.filters {
		splits := strings.SplitN(f, "=", 2)
		if len(splits) == 2 {
			name, val := strings.TrimSpace(strings.Title(splits[0])), strings.TrimSpace(splits[1])
			key := ColumnDefinitions(b.headers).resolveKey(name)

			if key != "" {
				funcs = append(funcs, graph.BuildPropertyFilterFunc(key, val))
			}
		}

	}
	return
}

func (b *Builder) buildGraphTagFilters() (funcs []graph.FilterFn) {
	for _, f := range b.tagFilters {
		splits := strings.SplitN(f, "=", 2)
		if len(splits) == 2 {
			key, val := strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1])
			funcs = append(funcs, graph.BuildTagFilterFunc(key, val))
		}
	}
	return
}

func (b *Builder) buildGraphTagKeyFilters() (funcs []graph.FilterFn) {
	for _, k := range b.tagKeyFilters {
		funcs = append(funcs, graph.BuildTagKeyFilterFunc(k))
	}
	return
}

func (b *Builder) buildGraphTagValueFilters() (funcs []graph.FilterFn) {
	for _, v := range b.tagValueFilters {
		funcs = append(funcs, graph.BuildTagValueFilterFunc(v))
	}
	return
}

func (b *Builder) Build() (Displayer, error) {
	base := fromGraphDisplayer{sorter: &defaultSorter{sortBy: b.sort}, rdfType: b.rdfType, headers: b.headers, maxwidth: b.maxwidth}

	switch b.dataSource.(type) {
	case *graph.Graph:
		gph := b.dataSource.(*graph.Graph)
		filteredGraph, err := gph.Filter(b.rdfType, b.buildGraphFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.Filter(b.rdfType, b.buildGraphTagFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.OrFilter(b.rdfType, b.buildGraphTagKeyFilters()...)
		if err != nil {
			return nil, err
		}

		filteredGraph, err = filteredGraph.OrFilter(b.rdfType, b.buildGraphTagValueFilters()...)
		if err != nil {
			return nil, err
		}

		if b.rdfType == "" {
			switch b.format {
			case "table":
				dis := &multiResourcesTableDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			case "json":
				dis := &multiResourcesJSONDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			case "porcelain":
				dis := &porcelainDisplayer{base}
				dis.setGraph(gph)
				return dis, nil
			default:
{'fraction_non_alphanumeric': 0.12710587590740993, 'fraction_numerical': 0.005752636625119847, 'mean_word_length': 3.633248730964467, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4782495', 'n_tokens_mistral': 2708, 'n_tokens_neox': 2503, 'n_words': 653}