<!DOCTYPE html>

<html lang="en">
  <head>
    <script src="https://polygit.org/polymer+^1.9.1/webcomponentsjs+^0.7.0/components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="challenge-element.html">
  </head>
  <body>
    <challenge-element name='0' age=34></challenge-element>
  </body>
</html>
<link rel="import" href="https://polygit.org/polymer+^1.9.1/webcomponentsjs+^0.7./components/polymer/polymer.html"/>
<dom-module id="challenge-element">
    <template>
        <h3>[[name]] average age ([[age]]) and count ([[count]])</h3>
        <div>{{years}} years of experience:</div>
        <br/>
        <i>{{explanation}}</i>
    </template>
    <script>
        Polymer({
            is: 'challenge-element',

            properties: {
                name: {type: String},
                age: {type: Number, value: -1},
                count: {type: Number, value: -1},
                years: {type: Number, value: 0},
                explanation: {type: String, value: 'no more detail'},
            },

            ready: function () {
                var name = this.name;
                if (this.name == false) {
                    this.name = 'polymer';
                    name = this.name;
                }

                // With callback :
                // someFetch('https://api.genderize.io/?name=' + name, function (data) {
                //    this.count = data.count;
                // });
                // With promise :
                fetch('https://api.genderize.io/?name=' + name)
                    .then((response) => response.json())
                    .then(function (data) {
                        this.count = data.count;
                    });
                

                if (this.age == -1) {
                    fetch('https://api.agify.io/?name=' + name)
                        .then((response) => response.json())
                        .then(function (data) {
                            this.age = data.age;
                        });
                }

                this.years = this.age * this.count;

                fetch('https://cat-fact.herokuapp.com/facts/random?amount=' + this.years)
                    .then(response => response.json())
                    .then(function (data) {
                        if (data.length > 2) {
                            this.explanation = data[2].text;
                        }
                    });
            },
        });
    </script>
</dom-module>